package com.service.impl;

import com.domain.Role;
import com.mapper.RoleMapper;
import com.qo.PageResult;
import com.qo.QueryObject;
import com.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author shkstart
 * @create 2022/3/11-11:30
 */
@Transactional
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper mapper;

    @Override
    public void delete(Long id) {
        //删除关系
        mapper.deleteRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Role role, Long[] roleIds) {
        //保存之后就会有id
        mapper.insert(role);
        //然后根据id插入
        if (roleIds != null && roleIds.length > 0) {
            for (Long roleId : roleIds) {
                mapper.insertRelation(role.getId(),roleId);
            }
        }
    }

    @Override
    public Role get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> listAll() {
        return mapper.selectAll();
    }

    @Override
    public void update(Role role, Long[] permissionIds) {
        mapper.updateByPrimaryKey(role);
        //删除关系
        mapper.deleteRelation(role.getId());
        //关联关系
        if (permissionIds != null && permissionIds.length > 0) {
            for (Long permissionId : permissionIds) {
                mapper.insertRelation(role.getId(), permissionId);
            }
        }
    }

    @Override
    public PageResult<Role> query(QueryObject qo) {
        int count = mapper.selectForCournt(qo);
        if (count == 0){
            return new PageResult<>(count);
            //new PageResult<>(qo.getCurrentPage(), count, Collections.emptyList(), qo.getPageSize());
        }
        //获取到总页数
        int totalPage = count % qo.getPageSize() == 0 ? count / qo.getPageSize() : count / qo.getPageSize() + 1;
        //判断当前页是否大于总页数，如果大于，则将最后一页（总页数）作为当前页，来查询分页结果
        if (qo.getCurrentPage() > totalPage)
            qo.setCurrentPage(totalPage);
        //当查询有数据时
        List<Role> list = mapper.selectLimitList(qo);
        return new PageResult<>(qo.getCurrentPage(),count,list,qo.getPageSize());
    }
}
